<template>
  <div class="responsive-layout" :class="layoutClasses">
    <!-- 移动端侧边栏遮罩 -->
    <div
      v-show="isMobileDevice && sidebarVisible"
      class="sidebar-overlay"
      @click="hideSidebar"
    ></div>

    <!-- 侧边栏 -->
    <aside
      class="sidebar"
      :class="sidebarClasses"
      :style="sidebarStyles"
    >
      <slot name="sidebar">
        <div class="sidebar-content">
          <!-- 侧边栏头部 -->
          <div class="sidebar-header">
            <div class="logo">
              <h2>AI-SOES</h2>
              <p v-if="!isMobileDevice">智能在线考试系统</p>
            </div>
            <el-button
              v-if="isMobileDevice"
              :icon="Close"
              circle
              @click="hideSidebar"
            />
          </div>

          <!-- 导航菜单 -->
          <el-menu
            :default-active="activeMenu"
            :collapse="isCollapsed"
            :unique-opened="true"
            class="sidebar-menu"
            @select="handleMenuSelect"
          >
            <template v-for="item in menuItems" :key="item.path">
              <el-sub-menu v-if="item.children" :index="item.path">
                <template #title>
                  <el-icon><component :is="item.icon" /></el-icon>
                  <span>{{ item.title }}</span>
                </template>
                <el-menu-item
                  v-for="child in item.children"
                  :key="child.path"
                  :index="child.path"
                >
                  <el-icon><component :is="child.icon" /></el-icon>
                  <span>{{ child.title }}</span>
                </el-menu-item>
              </el-sub-menu>
              <el-menu-item v-else :index="item.path">
                <el-icon><component :is="item.icon" /></el-icon>
                <span>{{ item.title }}</span>
              </el-menu-item>
            </template>
          </el-menu>

          <!-- 侧边栏底部 -->
          <div class="sidebar-footer" v-if="!isMobileDevice">
            <el-button
              :icon="isCollapsed ? Expand : Fold"
              circle
              @click="toggleSidebar"
            />
          </div>
        </div>
      </aside>

    <!-- 主内容区域 -->
    <div class="main-content" :class="mainContentClasses">
      <!-- 顶部导航 -->
      <header class="header" :class="headerClasses">
        <div class="header-left">
          <el-button
            v-if="isMobileDevice"
            :icon="Menu"
            circle
            @click="showSidebar"
          />
          <el-button
            v-else-if="isCollapsed"
            :icon="Expand"
            circle
            @click="expandSidebar"
          />
          <h1 class="page-title">{{ pageTitle }}</h1>
        </div>

        <div class="header-center">
          <slot name="header-center"></slot>
        </div>

        <div class="header-right">
          <slot name="header-right">
            <el-dropdown @command="handleUserCommand">
              <div class="user-info">
                <el-avatar :size="32" :src="userAvatar">
                  {{ userName?.charAt(0).toUpperCase() }}
                </el-avatar>
                <span class="user-name" v-if="!isMobileDevice">{{ userName }}</span>
                <el-icon class="user-arrow"><ArrowDown /></el-icon>
              </div>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="profile">
                    <el-icon><User /></el-icon>
                    个人中心
                  </el-dropdown-item>
                  <el-dropdown-item command="settings">
                    <el-icon><Setting /></el-icon>
                    系统设置
                  </el-dropdown-item>
                  <el-dropdown-item command="logout" divided>
                    <el-icon><SwitchButton /></el-icon>
                    退出登录
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </slot>
        </div>
      </header>

      <!-- 面包屑导航 -->
      <div class="breadcrumb-container" v-if="showBreadcrumb">
        <el-breadcrumb separator="/">
          <el-breadcrumb-item
            v-for="item in breadcrumbs"
            :key="item.path"
            :to="item.path"
          >
            {{ item.title }}
          </el-breadcrumb-item>
        </el-breadcrumb>
      </div>

      <!-- 页面内容 -->
      <main class="page-content" :class="pageContentClasses">
        <div class="content-wrapper">
          <slot></slot>
        </div>
      </main>
    </div>

    <!-- 移动端底部导航 -->
    <nav v-if="isMobileDevice && showBottomNav" class="bottom-nav">
      <div
        v-for="item in bottomNavItems"
        :key="item.path"
        class="bottom-nav-item"
        :class="{ active: isActiveBottomNav(item) }"
        @click="navigateTo(item.path)"
      >
        <el-icon><component :is="item.icon" /></el-icon>
        <span>{{ item.title }}</span>
      </div>
    </nav>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useAuthStore } from '@/stores/auth'
import { useResponsive } from '@/composables/useResponsive'
import {
  Close, Menu, Expand, Fold, ArrowDown, User, Setting, SwitchButton,
  House, Document, TrendCharts, UserFilled, Files, DataBoard
} from '@element-plus/icons-vue'

interface Props {
  pageTitle?: string
  showBreadcrumb?: boolean
  showBottomNav?: boolean
  sidebarCollapsed?: boolean
}

const props = withDefaults(defineProps<Props>(), {
  pageTitle: '',
  showBreadcrumb: true,
  showBottomNav: true,
  sidebarCollapsed: false
})

const emit = defineEmits<{
  sidebarToggle: [collapsed: boolean]
}>()

const router = useRouter()
const route = useRoute()
const authStore = useAuthStore()
const { isMobileDevice, isTabletDevice, getValue } = useResponsive()

// 响应式状态
const sidebarVisible = ref(false)
const isCollapsed = ref(props.sidebarCollapsed)

// 计算属性
const layoutClasses = computed(() => ({
  'mobile': isMobileDevice.value,
  'tablet': isTabletDevice.value,
  'sidebar-visible': sidebarVisible.value,
  'sidebar-collapsed': isCollapsed.value
}))

const sidebarClasses = computed(() => ({
  'collapsed': isCollapsed.value,
  'visible': sidebarVisible.value,
  'mobile': isMobileDevice.value
}))

const sidebarStyles = computed(() => {
  if (isMobileDevice.value) {
    return {
      width: getValue({ xs: '280px', sm: '280px' }, '280px')
    }
  }
  return {
    width: isCollapsed.value
      ? getValue({ md: '60px', lg: '64px', xl: '64px' }, '64px')
      : getValue({ md: '240px', lg: '260px', xl: '280px' }, '280px')
  }
})

const mainContentClasses = computed(() => ({
  'sidebar-collapsed': isCollapsed.value,
  'mobile': isMobileDevice.value
}))

const headerClasses = computed(() => ({
  'mobile': isMobileDevice.value,
  'sidebar-collapsed': isCollapsed.value
}))

const pageContentClasses = computed(() => ({
  'with-bottom-nav': isMobileDevice.value && props.showBottomNav,
  'mobile': isMobileDevice.value
}))

const userName = computed(() => authStore.user?.name || authStore.user?.username || '用户')
const userAvatar = computed(() => authStore.user?.avatar || '')

const activeMenu = computed(() => route.path)

// 菜单项
const menuItems = ref([
  {
    title: '首页',
    path: '/dashboard',
    icon: 'House'
  },
  {
    title: '题库管理',
    path: '/questions',
    icon: 'Files',
    children: [
      { title: '题库列表', path: '/questions/banks', icon: 'Document' },
      { title: '题目管理', path: '/questions/list', icon: 'Document' }
    ]
  },
  {
    title: '考试管理',
    path: '/examinations',
    icon: 'Document',
    children: [
      { title: '考试列表', path: '/examinations/list', icon: 'Document' },
      { title: '创建考试', path: '/examinations/create', icon: 'Document' }
    ]
  },
  {
    title: '成绩管理',
    path: '/grading',
    icon: 'TrendCharts',
    children: [
      { title: '成绩单', path: '/grading/sheets', icon: 'DataBoard' },
      { title: '成绩分析', path: '/grading/analysis', icon: 'TrendCharts' }
    ]
  },
  {
    title: '试卷管理',
    path: '/exam-paper',
    icon: 'Document',
    children: [
      { title: '模板管理', path: '/exam-paper/templates', icon: 'Document' },
      { title: '试卷管理', path: '/exam-paper/papers', icon: 'Files' }
    ]
  },
  {
    title: '系统设置',
    path: '/settings',
    icon: 'Setting',
    children: [
      { title: '个人设置', path: '/settings/profile', icon: 'UserFilled' },
      { title: '系统配置', path: '/settings/system', icon: 'Setting' }
    ]
  }
])

// 底部导航项
const bottomNavItems = ref([
  { title: '首页', path: '/dashboard', icon: 'House' },
  { title: '考试', path: '/examinations/list', icon: 'Document' },
  { title: '成绩', path: '/grading/sheets', icon: 'TrendCharts' },
  { title: '我的', path: '/settings/profile', icon: 'User' }
])

// 面包屑
const breadcrumbs = computed(() => {
  const matched = route.matched.filter(item => item.meta?.title)
  return [
    { path: '/dashboard', title: '首页' },
    ...matched.map(item => ({
      path: item.path,
      title: item.meta?.title as string
    }))
  ]
})

// 方法
const showSidebar = () => {
  sidebarVisible.value = true
  document.body.style.overflow = 'hidden'
}

const hideSidebar = () => {
  sidebarVisible.value = false
  document.body.style.overflow = ''
}

const toggleSidebar = () => {
  isCollapsed.value = !isCollapsed.value
  emit('sidebarToggle', isCollapsed.value)
}

const expandSidebar = () => {
  isCollapsed.value = false
  emit('sidebarToggle', false)
}

const handleMenuSelect = (index: string) => {
  router.push(index)
  if (isMobileDevice.value) {
    hideSidebar()
  }
}

const handleUserCommand = (command: string) => {
  switch (command) {
    case 'profile':
      router.push('/settings/profile')
      break
    case 'settings':
      router.push('/settings/system')
      break
    case 'logout':
      authStore.logout()
      router.push('/login')
      break
  }
}

const navigateTo = (path: string) => {
  router.push(path)
}

const isActiveBottomNav = (item: any): boolean => {
  return route.path.startsWith(item.path)
}

const handleResize = () => {
  if (!isMobileDevice.value && sidebarVisible.value) {
    hideSidebar()
  }
}

// 生命周期
onMounted(() => {
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
  document.body.style.overflow = ''
})
</script>

<style scoped>
.responsive-layout {
  display: flex;
  min-height: 100vh;
  background-color: var(--el-bg-color-page);
}

.sidebar-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  z-index: 1000;
  transition: opacity 0.3s ease;
}

.sidebar {
  position: fixed;
  top: 0;
  left: 0;
  height: 100vh;
  background: var(--el-bg-color);
  border-right: 1px solid var(--el-border-color-lighter);
  z-index: 1001;
  transition: all 0.3s ease;
  display: flex;
  flex-direction: column;
}

.sidebar.mobile {
  transform: translateX(-100%);
}

.sidebar.mobile.visible {
  transform: translateX(0);
}

.sidebar.collapsed {
  width: 64px !important;
}

.sidebar-content {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.sidebar-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px;
  border-bottom: 1px solid var(--el-border-color-lighter);
}

.logo h2 {
  margin: 0;
  color: var(--el-color-primary);
  font-size: 18px;
}

.logo p {
  margin: 4px 0 0 0;
  font-size: 12px;
  color: var(--el-text-color-secondary);
}

.sidebar-menu {
  flex: 1;
  border-right: none;
  overflow-y: auto;
}

.sidebar-footer {
  padding: 16px;
  border-top: 1px solid var(--el-border-color-lighter);
  display: flex;
  justify-content: center;
}

.main-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  transition: margin-left 0.3s ease;
  margin-left: 280px;
}

.main-content.mobile {
  margin-left: 0;
}

.main-content.sidebar-collapsed {
  margin-left: 64px;
}

.header {
  position: sticky;
  top: 0;
  z-index: 100;
  background: var(--el-bg-color);
  border-bottom: 1px solid var(--el-border-color-lighter);
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 24px;
  height: 64px;
}

.header.mobile {
  padding: 0 16px;
  height: 56px;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 16px;
}

.page-title {
  margin: 0;
  font-size: 20px;
  color: var(--el-text-color-primary);
}

.header.mobile .page-title {
  font-size: 18px;
}

.header-center {
  flex: 1;
  display: flex;
  justify-content: center;
}

.header-right {
  display: flex;
  align-items: center;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
  padding: 8px 12px;
  border-radius: 8px;
  transition: background-color 0.3s ease;
}

.user-info:hover {
  background-color: var(--el-fill-color-light);
}

.user-name {
  font-size: 14px;
  color: var(--el-text-color-primary);
}

.user-arrow {
  color: var(--el-text-color-secondary);
  transition: transform 0.3s ease;
}

.breadcrumb-container {
  padding: 16px 24px;
  background: var(--el-bg-color);
  border-bottom: 1px solid var(--el-border-color-lighter);
}

.breadcrumb-container.mobile {
  padding: 12px 16px;
}

.page-content {
  flex: 1;
  padding: 24px;
  overflow-y: auto;
}

.page-content.mobile {
  padding: 16px;
}

.page-content.with-bottom-nav {
  padding-bottom: 80px;
}

.content-wrapper {
  max-width: 1200px;
  margin: 0 auto;
}

.bottom-nav {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: var(--el-bg-color);
  border-top: 1px solid var(--el-border-color-lighter);
  display: flex;
  justify-content: space-around;
  padding: 8px 0;
  z-index: 100;
  backdrop-filter: blur(10px);
  -webkit-backdrop-filter: blur(10px);
}

.bottom-nav-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 4px;
  padding: 8px 16px;
  cursor: pointer;
  transition: all 0.3s ease;
  color: var(--el-text-color-secondary);
  min-width: 60px;
}

.bottom-nav-item.active {
  color: var(--el-color-primary);
}

.bottom-nav-item .el-icon {
  font-size: 20px;
}

.bottom-nav-item span {
  font-size: 12px;
  font-weight: 500;
}

/* 响应式优化 */
@media (max-width: 768px) {
  .sidebar-header {
    padding: 12px 16px;
  }

  .logo h2 {
    font-size: 16px;
  }

  .logo p {
    font-size: 10px;
  }

  .sidebar-menu {
    padding: 8px 0;
  }

  .el-menu-item,
  .el-sub-menu__title {
    height: 48px;
    line-height: 48px;
  }

  .header-center {
    display: none;
  }

  .content-wrapper {
    max-width: 100%;
  }
}

@media (max-width: 480px) {
  .page-content.mobile {
    padding: 12px;
  }

  .breadcrumb-container.mobile {
    padding: 8px 12px;
  }
}

/* 暗色主题支持 */
@media (prefers-color-scheme: dark) {
  .bottom-nav {
    background: rgba(0, 0, 0, 0.8);
  }
}

/* 安全区域适配 */
@supports (padding: max(0px)) {
  .bottom-nav {
    padding-bottom: max(8px, env(safe-area-inset-bottom));
  }

  .page-content.with-bottom-nav {
    padding-bottom: max(80px, calc(80px + env(safe-area-inset-bottom)));
  }
}
</style>